#!/usr/bin/python -S
"""
chunks.py

Analog of lines.py for netstrings
"""

__author__ = 'Andy Chu'


import sys
import optparse


def CreateOptionsParser():
  parser = optparse.OptionParser()

  # TODO:
  # Also do -0, which parses find -0 input

  parser.add_option(
      '-t', '--type', dest='type', type='str', default='\n',
      help='TNET character type to use (, # ^ $ etc.)')
  parser.add_option(
      '--lines', dest='lines', action='store_true', default=False,
      help='Make each input line an element')
  parser.add_option(
      '--words', dest='words', action='store_true', default=False,
      help='Make each whitespace-separated word an element')

  return parser


def main(argv):
  (options, argv) = CreateOptionsParser().parse_args(argv)

  stream = argv[1:]
  if not stream:
    if options.lines:
      if not stream:
        stream = (line.strip() for line in sys.stdin)
    elif options.words:
      # split on words
      stream = sys.stdin.read().split()
    else:
      # all of stdin as a single word
      stream = [sys.stdin.read()]

  for arg in stream:
    s = '%d:%s%s' % (len(arg), arg, options.type)
    sys.stdout.write(s)
  return 0


if __name__ == '__main__':
  try:
    sys.exit(main(sys.argv))
  except RuntimeError, e:
    print >> sys.stderr, e.args[0]
    sys.exit(1)
